package com.learn.Stream;

import java.util.concurrent.RecursiveTask;

/**
 * ForkJoin使用实例
 *
 * 特征:
 * 1.大数据量汇总合并计算返回本直接和递归类似
 * 2.工作窃取 优点大于缺点
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

    private long begin;
    private long end;

    private Long contion;

    public ForkJoinDemo(long begin, long end,long contion) {
        this.begin = begin;
        this.end = end;
        this.contion = contion;
    }

    @Override
    protected Long compute() {
        if((end-begin) < contion){
            long sum = 0l;
            for (long i = begin; i <= end; i++) {
                sum += i;
            }
            return sum;
        }else{
            long middle = (end+begin) / 2;
            ForkJoinDemo f1 = new ForkJoinDemo(begin,middle,contion);
            f1.fork();
            ForkJoinDemo f2 = new ForkJoinDemo(middle+1,end,contion);
            f2.fork();
            return f2.join()+f1.join();
        }
    }
}
